package com.example.mycityapp;

import com.example.mycityapp.util.ImgurUploadTask;
import com.google.android.gms.maps.model.BitmapDescriptor;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;



public class BrowsePictureActivity extends Activity {

    // this is the action code we use in our intent, 
    // this way we know we're looking at the response from our own action
	public enum BrowsePictureForWhat
	{
		None,
		NewPostPage,
		ProfilePage
	}
	
	public static BrowsePictureForWhat browseType = BrowsePictureForWhat.None;
	private BrowsePictureForWhat browseTypePrivate;
	
    private static final int SELECT_PICTURE = 1;

    private String selectedImagePath;
    
    private Uri selectedImageUri;
    
    private ImgurUploadTask uploader;

    @SuppressLint("NewApi")
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.select_picture);
       
        Log.d("BROWSEPICTUREWHYCLOSED", browseType.toString());
        browseTypePrivate = browseType;
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        
        

        ((Button)findViewById(R.id.selectPictureButton) )
                .setOnClickListener(new OnClickListener() {

                    public void onClick(View arg0) {

                        // in onCreate or any event where your want the user to
                        // select a file
                        Intent intent = new Intent();
                        intent.setType("image/*");
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(Intent.createChooser(intent,
                                "Select Picture"), SELECT_PICTURE);
                    }
                });
        
        ((Button)findViewById(R.id.uploadPictureButton) )
        .setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {

            	
                String id = uploader.upload();
                if (browseTypePrivate == BrowsePictureForWhat.NewPostPage)
                {
                	NewPostPage.imgurId = id;
                }
                else if (browseTypePrivate == BrowsePictureForWhat.ProfilePage)
                {
                	Log.d("BROWSEPICTURE", "PROFILEPAGE HTTPPOST");
                	ProfilePage.imgurIdForChangedProfilePic = id;
                	String urlChangeProfilePic = "http://titan.cmpe.boun.edu.tr:8087/MyCity/services/user/changeProfilePic?"
                			+ "userId=" + MainActivity.userId + "&profilePic=" + id;
                	JSONParser jParser = new JSONParser();
                	String jsonChangeProfilePic = jParser.doInBackground(urlChangeProfilePic);
                	if (jsonChangeProfilePic.contains("1"))
    				{
    					AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(BrowsePictureActivity.this);

                        dlgAlert.setMessage("Profile picture changed.");
                        dlgAlert.setTitle("Success");
                        dlgAlert.setPositiveButton("OK", null);
                        dlgAlert.setCancelable(true);
                        dlgAlert.create().show();

                        dlgAlert.setPositiveButton("Ok",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {

                            }
                        });
    				}
    				else
    				{
    					AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(BrowsePictureActivity.this);

                        dlgAlert.setMessage("Request failed. Sorry :(");
                        dlgAlert.setTitle("Error");
                        dlgAlert.setPositiveButton("OK", null);
                        dlgAlert.setCancelable(true);
                        dlgAlert.create().show();

                        dlgAlert.setPositiveButton("Ok",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                	
                            }
                        });
    				}
                }
                
                TextView txt = (TextView) findViewById(R.id.imgurId);
                txt.setText(id);
                if (browseTypePrivate != BrowsePictureForWhat.ProfilePage)
                {
                	Log.d("BROWSEPICTUREWHYCLOSED", browseTypePrivate.toString());
                	Log.d("BROWSEPICTUREWHYCLOSED", "BYEEEE");
                	BrowsePictureActivity.this.finish();
                }
            }
        });
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_PICTURE) {
                selectedImageUri = data.getData();
                selectedImagePath = getPath(selectedImageUri);
                uploader = new ImgurUploadTask(selectedImageUri, this);
                ImageView imToUpload = (ImageView) findViewById(R.id.imageToUpload);
                imToUpload.setImageURI(selectedImageUri);
            }
        }
    }

    /**
     * helper to retrieve the path of an image URI
     */
    public String getPath(Uri uri) {
            // just some safety built in 
            if( uri == null ) {
                // TODO perform some logging or show user feedback
                return null;
            }
            // try to retrieve the image from the media store first
            // this will only work for images selected from gallery
            String[] projection = { MediaStore.Images.Media.DATA };
            Cursor cursor = managedQuery(uri, projection, null, null, null);
            if( cursor != null ){
                int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
            }
            // this is our fallback here
            return uri.getPath();
    }

}